<template>
	<view>
		<view class="category-menu">
			<scroll-view scroll-x="true" class="category-scroll">
				<view class="category-item" v-for="(item, index) in categorys" :key="item" :class="selectedCategoryId === item ? 'active' : ''" @click="changeCategory(item)">
					<view>{{ item }}</view>
				</view>
			</scroll-view>
		</view>

		<scroll-view scroll-y="true" class="scroll-container">
			<!-- 用户列表 (一行四列) -->
			<view v-if="selectedCategoryId === '普通用户'">
				<view v-for="(group, groupIndex) in groupMembers(members)" :key="groupIndex" class="table-row">
					<view v-for="(member, memberIndex) in group" :key="`${groupIndex}-${memberIndex}`">
						<view class="table-cell">
							<view class="avatar" @click="getuserinfo(member.userId)">
								<image class="pic" :src="(member.nicPic && member.nicPic.url) || '/static/none.png'" mode="aspectFill" @error="onImageError"></image>
							</view>
							<view class="text">
								<text>{{ member.nicName || member.userId }}</text>
							</view>
						</view>
					</view>
					<!-- 补齐最后一行空位 -->
					<view v-if="group.length < 4" v-for="i in 4 - group.length" :key="`empty-${groupIndex}-${i}`" class="table-cell empty"></view>
				</view>
			</view>

			<!-- 商家列表 (一行两列) -->
			<view class="shop-container" v-else>
				<!-- 左列 -->
				<view class="shop-column">
					<!-- 修正：原 shop-item-wrapper → shop-column -->
					<view class="shopclass" v-for="(item, index) in shopList.left" :key="item.id">
						<view class="shop-item">
							<!-- 商家卡片内容（图片、名称、信息）保持不变 -->
							<view class="image-container">
								<image
									class="shop-image"
									:src="item.photos && item.photos.length > 0 ? item.photos[0].url : '/static/none.png'"
									mode="aspectFill"
									@error="onImageError"
								/>
								<view class="name_type">
									<text class="shop-name">{{ item.title }}</text>
									<text class="shop-type">类型：{{ item.category }}</text>
								</view>
							</view>
							<view class="shop-info">
								<text class="shop-address" v-if="item.address">地址：{{ item.address }}</text>
								<text class="shop-time" v-if="item.business && item.business.opentime_today">营业时间：{{ item.business.opentime_today }}</text>
								<text class="shop-distance">离您：{{ formatDistance(item.location) }}</text>
								<text class="shop-tel" v-if="item.business && item.business.tel">电话：{{ item.business.tel }}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 右列 -->
				<view class="shop-column">
					<!-- 修正：原 shop-item-wrapper → shop-column -->
					<view class="shopclass" v-for="(item, index) in shopList.right" :key="item.id">
						<view class="shop-item">
							<!-- 商家卡片内容与左列一致，保持不变 -->
							<view class="image-container">
								<image
									class="shop-image"
									:src="item.photos && item.photos.length > 0 ? item.photos[0].url : '/static/none.png'"
									mode="aspectFill"
									@error="onImageError"
								/>
								<view class="name_type">
									<text class="shop-name">{{ item.title }}</text>
									<text class="shop-type">类型：{{ item.category }}</text>
								</view>
							</view>
							<view class="shop-info">
								<text class="shop-address" v-if="item.address">地址：{{ item.address }}</text>
								<text class="shop-time" v-if="item.business && item.business.opentime_today">营业时间：{{ item.business.opentime_today }}</text>
								<text class="shop-distance">离您：{{ formatDistance(item.location) }}</text>
								<text class="shop-tel" v-if="item.business && item.business.tel">电话：{{ item.business.tel }}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 无数据提示 -->
				<view v-if="filteredList.length === 0" class="no-data">
					<text>暂无相关数据</text>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<!-- script 和 style 部分与原代码一致，此处省略 -->

<script>
const db = uniCloud.databaseForJQL();
import { distance_m } from '../../utils/distance';

export default {
	data() {
		return {
			members: [],
			shopData: [],
			userInfo: {},

			categorys: [],
			selectedCategoryId: '',
			userId: '',
			filteredList: [] // 缓存过滤后的商家列表
		};
	},
	watch: {
		selectedCategoryId: {
			handler(newval) {
				this.filteredList = this.shopData.filter((item) => item.category === newval);
			}
		}
	},

	computed: {
		shopList() {
			const left = [];
			const right = [];
			this.filteredList.forEach((item, index) => {
				if (index % 2 === 0) {
					left.push(item);
				} else {
					right.push(item);
				}
			});
			return { left, right };
		},
		markers() {
			return this.$store.state.msg.markers;
		},
		storeData() {
			return this.$store.state.msg;
		}
	},
	async onLoad(res) {
		try {
			console.log('33333', res.key);
			const key = res.key;
			this.FromData = this.markers;

			this.categorys = this.getGategorys(this.FromData);
			const userIds = this.FromData.filter((item) => item.keytag === '普通用户').map((item) => item.id);
			const shopIds = this.FromData.filter((item) => item.keytag !== '普通用户').map((item) => item.id);
			await this.getUsers(userIds);
			await this.getShops(shopIds);

			if (key) {
				this.selectedCategoryId = key;
			}
		} catch (error) {
			console.error('解析成员信息失败:', error);
			this.members = [];
		}
	},
	methods: {
	
		// 图片加载失败处理
		onImageError(e) {
			console.log('图片加载失败', e);
			// 可以在这里设置默认图片
		},
		getGategorys(data) {
			const keytagSet = new Set();
			data.forEach((item) => {
				if (item.keytag !== '收藏点') {
					keytagSet.add(item.keytag);
				}
			});
			console.log('分类', Array.from(keytagSet));
			return Array.from(keytagSet);
		},
		async getUsers(userIds) {
			console.log('普通用户', userIds);
			if (!userIds || userIds.length === 0) return;

			try {
				const res = await db
					.collection('linli-user')
					.where({
						userId: db.command.in(userIds)
					})
					.get();
				if (res.data.length > 0) {
					this.members = res.data;
				}
			} catch (e) {
				console.error('获取用户信息失败:', e);
			}
		},
		/**
		 * 根据商家ID批量获取商家信息
		 * @param {Array} ids - 商家ID数组（如 ['shop1', 'shop2']）
		 * @returns {Promise<void>} - 无返回值，直接更新this.shopData
		 */
		async getShops(ids) {
			// 1. 严格校验入参：确保ids是数组且非空
			if (!Array.isArray(ids) || ids.length === 0) {
				console.warn('getShops：请传入非空的商家ID数组');
				this.shopData = []; // 重置为空数组，避免旧数据残留
				return;
			}

			try {
				// 2. 数据库查询：使用in筛选指定ID的商家
				const res = await db
					.collection('sendshop')
					.where({
						sendshopId: db.command.in(ids) // 注意：若sendshopId是数字类型，需确保ids元素也是数字
					})
					.get();
				console.log('店铺', res);
				// 3. 处理查询结果：过滤+排序+空值兼容
				const rawShopData = res.data || []; // 兼容res.data为undefined的情况
				// 过滤：只保留有图片的商家（photos是数组且长度>0）
				const filteredShops = rawShopData.filter((item) => Array.isArray(item.photos) && item.photos.length > 0);
				// 排序：按distance升序（近→远），兼容distance为空的情况（空值排最后）
				this.shopData = filteredShops.sort((a, b) => {
					// 处理distance为空的情况：将undefined/null视为无穷大
					const distanceA = this.formatDistance(a.location) ?? Infinity;
					const distanceB = this.formatDistance(b.location) ?? Infinity;
					// 标准排序逻辑：返回-1/0/1，确保排序稳定
					return distanceA - distanceB;
				});
			} catch (e) {
				// 5. 错误处理：补充错误上下文，便于定位问题
				console.error('getShops：获取商家信息失败', {
					errorMsg: e.message,
					errorStack: e.stack,
					requestIds: ids // 打印请求的ID，便于排查数据库筛选问题
				});
				// 错误时重置数据，避免页面显示旧数据
				this.shopData = [];
			}
		},
		changeCategory(selectedItem) {
			this.selectedCategoryId = selectedItem;
		},
		groupMembers(members) {
			const grouped = [];
			for (let i = 0; i < members.length; i += 4) {
				grouped.push(members.slice(i, i + 4));
			}
			return grouped;
		},
		async getuserinfo(userId) {
			if (userId !== this.storeData.user.userId) {
				uni.navigateTo({
					url: `/pages/friend/friend?id=${userId}`
				});
				return;
			} else {
				uni.navigateTo({
					url: '/pages/me/me'
				});
			}
		},
		close() {
			this.$refs.popup.close();
		},
		formatDistance(location) {
			if (!location?.coordinates || !this.$store.state.msg.senderLocation) {
				return '未知';
			}
			const loc1 = this.$store.state.msg.senderLocation;
			const loc2 = {
				longitude: location.coordinates[0],
				latitude: location.coordinates[1]
			};
			return distance_m(loc1, loc2);
			// const dis=Math.round(distance_m(loc1, loc2)*1000)
			// return dis ;
		}
	}
};
</script>

<style lang="scss" scoped>
.scroll-container {
	margin-top: 85rpx;
	width: 750rpx;
	padding: 10rpx 25rpx;
	gap: 25rpx;
	box-sizing: border-box;
}

.category-scroll {
	position: fixed;
	left: 0;
	top: 0;
	white-space: nowrap;
	padding: 20rpx 20rpx;
	background: #fff;
	z-index: 10; /* 确保在内容上方 */
	width: 100%;
	box-sizing: border-box;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1); /* 添加阴影区分区域 */

	.category-item {
		display: inline-block;
		padding: 10rpx 30rpx;
		margin-right: 20rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
		color: #666;
		transition: all 0.3s;

		&.active {
			background: #e64340;
			color: #fff;
			font-weight: bold;
		}
	}
}

.table-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	overflow: hidden;
}

.shop-container {
	display: flex;
	padding: 10rpx 10rpx;
	gap: 20rpx; /* 两列之间的间距 */
	width: 100%;
	box-sizing: border-box;
}

/* 2. 两列容器：各占 50% 宽度，减去间距补偿 */
.shop-column {
	/* 原 shop-item-wrapper 重命名，语义更清晰 */
	width: calc(50% - 20rpx); /* 50%宽度 - 10rpx（间距的一半），确保总宽度不溢出 */
	display: flex;
	flex-direction: column;
	gap: 25rpx; /* 列内商家卡片的上下间距 */
}

/* 3. 商家卡片外层：移除多余样式，确保宽度100% */
.shopclass {
	display: flex;
	flex-direction: column;
	width: 100%; /* 强制占满父容器宽度 */
}

/* 4. 商家卡片主体：添加白色背景，避免被遮挡 */
.shop-item {
	width: 100%;
	background: #fff; /* 白色背景，显示卡片轮廓 */
	border-radius: 16rpx; /* 统一圆角，与图片容器呼应 */
	overflow: hidden; /* 确保子元素圆角生效 */
}

/* 5. 图片容器：修正顶部间距，与卡片顶部对齐 */
.image-container {
	position: relative;
	width: 100%;
	height: 350rpx; /* 固定图片高度，保持布局统一 */
	/* 移除 margin-top:25rpx，改为卡片内间距 */
	overflow: hidden;
}

/* 6. 商家信息区域：修正边框和间距 */
.shop-info {
	display: flex;
	flex-direction: column;
	border: 1rpx solid #eee;
	border-top: none; /* 与图片容器无缝衔接 */
	padding: 15rpx;
	font-size: 26rpx;
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
	box-shadow: 0 5rpx 10rpx rgba(0, 0, 0, 0.05);
	word-break: break-all;

	> text {
		margin-bottom: 8rpx;
		&:last-child {
			margin-bottom: 0;
		}
	}
}

.no-data {
	display: flex;
	flex-direction: column;
	height: 300rpx;
	justify-content: center;
	align-items: center;
	font-size: 32rpx;
	color: #999;
	width: 100%;
}

.table-cell {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	margin: 15rpx;
	width: 100rpx;
	border-radius: 10rpx;
}

.empty {
	visibility: hidden;
}

.pic {
	width: 100rpx;
	border-radius: 15rpx;
	height: 100rpx;
}

.avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 15rpx;
	overflow: hidden; /* 确保图片圆角生效 */
}

.text {
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 26rpx;
	width: 100rpx;
	padding: 5rpx 5rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	text-align: center;
}

.name_type {
	position: absolute;
	left: 0;
	right: 0;
	bottom: 0;
	background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
	color: white;
	padding: 20rpx 12rpx 12rpx;
	display: flex;
	flex-direction: column;
}

.shop-name {
	font-size: 30rpx;
	font-weight: bold;
	margin-bottom: 4rpx;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.5);
}

.shop-type {
	font-size: 26rpx;
	opacity: 0.9;
}

.shop-address,
.shop-time,
.shop-tel {
	color: #666;
}

.shop-distance {
	color: #e64340;
	font-weight: 500;
}
</style>
